<template>
    <div class="flex flex-wrap">
        <el-button-group class="w-full mb-2">
            <el-button type="primary" :icon="Refresh" @click="refreshFormeList">刷新</el-button>
            <el-button type="primary" :icon="AddSquare24Regular" @click="openDialog">新增</el-button>
            <el-button type="primary" :icon="DatabaseImport" @click="importForme" disabled>导入</el-button>
            <el-button type="primary" :icon="DatabaseExport" @click="exportForme" disabled>导出</el-button>
        </el-button-group>
        <div v-if="formeList.length > 0" class="w-full">
            <el-descriptions title="印版列表" :column="5" border>
                <div v-for="item in formeList" :key="item._id">
                    <el-descriptions-item label="客户名称"> {{ getCustomerName(item.customerId) }} </el-descriptions-item>
                    <el-descriptions-item label="产品名称"> {{ getProductName(item.productId) }} </el-descriptions-item>
                    <el-descriptions-item label="印版编号"> {{ item.formeNo }} </el-descriptions-item>
                    <el-descriptions-item label="印版备注"> {{ item.formeRemark }} </el-descriptions-item>
                    <el-descriptions-item label="操作">
                        <el-button type="primary" @click="handleEdit(item)">修改</el-button>
                        <el-button type="danger" @click="handleDelete(item)">删除</el-button>
                    </el-descriptions-item>
                </div>
            </el-descriptions>
        </div>
        <div v-else class="w-full">
            <el-empty description="暂无印版数据" />
        </div>
    </div>

    <el-dialog v-model="visible" :show-close="false" width="50%">
        <!-- 新增印版dialog标题 -->
        <template #header="{ close, titleId, titleClass }">
            <div class="my-header">
                <h4 :id="titleId" :class="titleClass">{{ dialogOption ? '新增印版' : '修改印版' }}</h4>
                <el-button type="danger" @click="close">
                    <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
                    关闭
                </el-button>
            </div>
        </template>
        <!-- 新增/修改 印版dialog内容 -->
        <el-form :model="forme" :rules="rules" ref="formeRef" label-width="120px" class="w-full">
            <el-form-item label="客户名称：" prop="customerId" required>
                <el-select v-model="forme.customerId" placeholder="请选择客户" filterable @change="getProductListEvent">
                    <el-option v-for="item in customerList" :key="item.customerAbbreviation" :label="item.customerName" :value="item.customerId" />
                </el-select>
            </el-form-item>
            <el-form-item label="产品名称：" prop="productId" required>
                <el-select v-model="forme.productId" placeholder="请选择产品" filterable>
                    <el-option v-for="item in productList" :key="item.productId" :label="item.productName" :value="item.productId" />
                </el-select>
            </el-form-item>
            <el-form-item label="印版编号：" prop="formeNo" required>
                <el-input v-model="forme.formeNo" placeholder="请输入印版编号" />
            </el-form-item>
            <el-form-item label="印版备注：" prop="formeRemark">
                <el-input type="textarea" v-model="forme.formeRemark" placeholder="请输入印版备注" />
            </el-form-item>
            <el-form-item>
                <el-button v-if="dialogOption" type="primary" @click="submitForm(formeRef)">提交</el-button>
                <el-button v-else type="primary" @click="updateFormEvent(formeRef)">提交</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script lang="ts" setup>
import { addForme, deleteForme, getFormeList, updateForme } from '@api/forme';
import { AddSquare24Regular } from '@vicons/fluent';
import { Refresh, DatabaseImport, DatabaseExport } from '@vicons/tabler';
import { CircleCloseFilled } from '@element-plus/icons-vue';
import { getAllCustomerList } from '@/api/customer';
import { FormInstance } from 'element-plus';
import { getAllProductList, getProductList } from '@/api/product';
import * as XLSX from 'xlsx';

onMounted(async () => {
    // 获取印版列表
    await refreshFormeList();

    // 获取客户列表
    const customerResult = await getAllCustomerList();
    customerResult.data.forEach((item) => {
        item.customerId = item._id;
        customerList.push(item);
    });

    // 获取所有产品列表
    const allProductResult = await getAllProductList();
    allProductResult.data.forEach((item) => {
        item.products.forEach((product) => {
            product.productId = product._id;
            allProductList.push(product);
        });
    });
});

/* ******************************通用数据/方法****************************** */
// 印版列表
const formeList = reactive<AjaxResponse['formeList']>([]);
// 客户列表
const customerList = reactive<AjaxResponse['customerList']>([]);
// 产品列表
const productList = reactive<AjaxResponse['productList']>([]);
// 所有产品列表
const allProductList = reactive<AjaxResponse['productList']>([]);

// 刷新印版列表
const refreshFormeList = async () => {
    // 清空印版列表
    formeList.length = 0;
    // 刷新印版列表
    getFormeList().then((res) => {
        res.data.forEach((item) => {
            formeList.push(item);
        });
    });
};
// 匹配客户名称
const getCustomerName = (customerId: string) => {
    const customer = customerList.find((item) => item._id === customerId);
    return customer?.customerName || '';
};
// 匹配产品名称
const getProductName = (productId: string) => {
    const product = allProductList.find((item) => item._id === productId);
    return product?.productName || '';
};

// 新增/修改 印版dialog方式
const dialogOption = ref(true);
// 被修改的印版Id
const updateFormeId = ref('');
// 新增/修改 印版
const handleEdit = (item: AjaxResponse['formeList'][number]) => {
    // 复制 item 到 forme
    Object.assign(forme, item);
    // 打开新增/修改 印版dialog
    visible.value = true;
    // 设置 dialog 方式为修改
    dialogOption.value = false;
    // 设置被修改的印版Id
    updateFormeId.value = item._id;
};

// 删除印版
const handleDelete = (item: AjaxResponse['formeList'][number]) => {
    // 确认删除
    ElMessageBox.confirm('确定删除该印版吗？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        // 删除印版
        deleteForme(item._id).then(() => {
            // 删除成功，提示用户删除成功
            ElMessage.success('删除成功');
            // 刷新印版列表
            refreshFormeList();
        });
    });
};

/* ******************************新增/修改 印版dialog表单****************************** */
// 新增印版dialog开关
const visible = ref(false);
// 表单的ref
const formeRef = ref<FormInstance>();
// 新增印版dialog表单数据
const forme = reactive({
    customerId: '',
    productId: '',
    formeNo: '',
    formeRemark: '/',
});
// 新增印版dialog表单校验规则
const rules = reactive({
    customerId: [{ required: true, message: '请选择客户', trigger: ['blur'] }],
    productId: [{ required: true, message: '请选择产品', trigger: ['blur'] }],
    formeNo: [{ required: true, message: '请输入印版编号', trigger: ['blur'] }],
});
// 打开新增/修改 印版dialog
const openDialog = () => {
    // 打开新增/修改 印版dialog
    visible.value = true;
    // 设置 dialog 方式为新增
    dialogOption.value = true;
    // 清空新增印版dialog表单数据
    Object.assign(forme, {
        customerId: '',
        productId: '',
        formeNo: '',
        formeRemark: '/',
    });
};
// 获取客户产品列表
const getProductListEvent = async (customerId: string) => {
    // 清空产品列表
    productList.length = 0;
    // 获取产品列表
    const productResult = await getProductList(customerId);
    productResult.data.forEach((item) => {
        // 获取客户产品列表
        item.productId = item._id;
        productList.push(item);
    });
};
// 提交新增印版dialog表单
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            // 提交新增印版dialog表单数据
            addForme(forme).then(() => {
                // 刷新印版列表
                refreshFormeList();
                visible.value = false;
            });
        } else {
            // 校验失败，提示用户输入正确信息
            ElMessage.error('请输入正确的信息');
        }
    });
};
// 更新印版dialog表单
const updateFormEvent = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    if (!updateFormeId.value) return;
    formEl.validate((valid) => {
        if (valid) {
            // 更新印版dialog表单数据
            updateForme(updateFormeId.value, forme).then(() => {
                // 刷新印版列表
                refreshFormeList();
                visible.value = false;
            });
        } else {
            // 校验失败，提示用户输入正确信息
            ElMessage.error('请输入正确的信息');
        }
    });
};

/* ******************************导入/导出 印版数据****************************** */
const importForme = () => {
    // 打开文件选择器
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.xlsx, .xls';
    input.click();

    // 监听文件选择器change事件
    input.addEventListener('change', (e) => {
        const file = (e.target as HTMLInputElement).files?.[0];
        if (!file) return;
        // 加载数据为arraybuffer
        const reader = new FileReader();
        reader.readAsArrayBuffer(file);
        // 读取结束事件
        reader.onload = () => {
            const arrayBuffer = reader.result as ArrayBuffer;
            // 转为Uint8Array
            const uint8Array = new Uint8Array(arrayBuffer);
            // 解析Excel文件
            const workbook = XLSX.read(uint8Array, { type: 'array' });
            // 获取第一个工作表
            const worksheet = workbook.Sheets[workbook.SheetNames[0]];
            // 转换为JSON格式
            const jsonData = XLSX.utils.sheet_to_json(worksheet);
            // 验证数据
            if (!jsonData || jsonData.length === 0) {
                ElMessage.error('Excel文件格式错误');
                return;
            }

            // 准备上传服务器的数据
            const uploadData: { customerId: string; productId: string }[] = [];
            for (let index = 0; index < jsonData.length; index++) {
                const item = jsonData[index] as any;

                console.log(item);
                // 匹配客户Id
                const customerInfo = customerList.find((i) => {
                    const reg = new RegExp(item['客户名称'], 'ig');
                    return reg.test(i.customerName);
                });

                if (!customerInfo) {
                    ElMessage.error(`客户名称${item['客户名称']}不存在`);
                    return;
                }
                // 匹配产品Id
                const productInfo = productList.find((i) => {
                    const reg = new RegExp(item['产品名称'], 'ig');
                    return reg.test(i.productName);
                });

                if (!productInfo) {
                    ElMessage.error(`${item['客户名称']} -> 产品名称：${item['产品名称']}不存在`);
                }
                uploadData.push({
                    customerId: customerInfo._id,
                    productId: productInfo ? productInfo._id : '/',
                });
            }

            console.log(uploadData);
        };
    });
};
// 导出印版数据
const exportForme = () => {
    // 导出印版数据
    // exportFormeData().then((res) => {
    //     // 导出成功，提示用户导出成功
    //     ElMessage.success('导出成功');
    //     // 下载导出文件
    //     downloadFile(res, '印版数据.xlsx');
    // });
};
</script>

<style lang="scss" scoped>
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}
</style>
